import getopt
import os
import shutil
import subprocess
import sys
import time
import traceback
from ConfigParser import SafeConfigParser

from Doc4 import *
from Repository import *

class Rsyncer(Doc4):
    
    def __init__(self):
        Doc4.__init__(self)
        self.logpath = self.config.get("rsync", "logfile")
        self.extractiondir = self.config.get("extraction", "outputdir")
        self.repositorydir = self.config.get("extraction", "mirror")

    def get_repository_file_list(self, repository):
            #repository_query = select distribution,provider,URL,port,username,password,architecture,branch,section from REPOSITORIES
            if repository.login is not None and len(repository.login.strip()) > 0:
                cmd = "export RSYNC_PASSWORD=%s; rsync --port=%s %s@%s | cut -d\":\" -f3 | cut -d\" \" -f2 | grep -v media_info" % (repository.password, repository.port, repository.login, repository.url)
            else:
                cmd = "rsync --port=%s %s | cut -d\":\" -f3 | cut -d\" \" -f2 | grep -v media_info" % (repository.port, repository.url)
            
            self.log("========== %s %s %s %s %s" % (repository.distribution, repository.provider, repository.architecture, repository.branch, repository.section)) 
            proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
            output = proc.communicate()[0]
            proc.wait()
            files = output.strip().split()
            package_files = []
            for file in files:
                ispackage = file.find(".rpm") > 0
                if ispackage:
                    package_files.append(file.strip())
            return package_files

    def rsync_files(self, repository):
        target = self.repositorydir+"/"+repository.provider+"/"+repository.distribution+"/"+repository.architecture+"/"+repository.branch+"/"+repository.section
        self.log("Target: %s" % target)
        if not os.path.exists(target):
            os.makedirs(target)
        #cmd = "rsync -auvH %s %s" % (repo[1], target)
        if repository.login is not None and len(repository.login.strip()) > 0:
            url = repository.url
            cmd = "export RSYNC_PASSWORD=%s; rsync -auvH --port=%s %s@%s --exclude-from=/home/doc4/mirror/excludes/repository-%d.exclude %s" % (repository.password, repository.port, repository.login, repository.url, repository.id_repository, target)
        else:
            cmd = "rsync -auvH --port=%s %s --exclude-from=/home/doc4/mirror/excludes/repository-%d.exclude %s" % (repository.port, repository.url, repository.id_repository, target)
        proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        output = proc.communicate()[0]
        proc.wait()
        print output.strip()

def main():
    rsyncer = Rsyncer()
    for repository_id in rsyncer.repository_ids:
        repository = rsyncer.get_repository(repository_id)
        rsyncer.rsync_files(repository)

if __name__ == "__main__":
    main()
